/*
 * Copyright (C) 2023, KylinSoft Co., Ltd.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
**/

#include "bluetoothmainwindow.h"

typedef QPair<QString,qint16> fruit;
//设备显示排序
QVector <fruit> devShowOrderListVec;
bool BlueToothMainWindow::m_device_operating = false;

BlueToothMainWindow::BlueToothMainWindow(QWidget *parent):
    QMainWindow(parent)
{
    KyDebug();

    btServer = new BlueToothDBusService(this);
    int res = btServer->initBluetoothServer();
    KyDebug() << "res:1-- init Bluetooth Server failed!";
    KyDebug() << "res:2-- Bluetooth adapter is null!";

    KyInfo() <<  "ukcc start -- res:" << res ;
    InitMainWindow();

    if (!res)
        InitInterfaceUIStatus();
    else
        _MCentralWidget->setCurrentIndex(MAINWINDOW_ERROR_ADAPTER_NOT_DETECTED);

    //绑定界面的ui信号
    InitInterfaceUISignalBinding();
    //绑定服务信号
    InitBluetoothServiceSignalBinding();
}

BlueToothMainWindow::~BlueToothMainWindow()
{
    KyDebug();

    btServer->deleteLater();
    _MCentralWidget->deleteLater();
    m_loadingWBTAdapterTimer->deleteLater();
    m_loadingWBTServiceTimer->deleteLater();

}

void BlueToothMainWindow::InitMainWindow()
{
    KyDebug();

    _MCentralWidget = new QStackedWidget(this);
    this->setCentralWidget(_MCentralWidget);

    InitAbnormalErrorWidget();
    InitNoAdapterErrorWidget();
    InitAdapterLoadingWidget();
    InitNormalWidget();

    _MCentralWidget->addWidget(_MAbnormalErrorWidget);
    _MCentralWidget->addWidget(_MNoAdapterErrorWidget);
    _MCentralWidget->addWidget(_MAdapterLoadingWidget);
    _MCentralWidget->addWidget(_MNormalWidget);
    _MCentralWidget->setCurrentIndex(MAINWINDOW_NORMAL_INTERFACE);


}

void BlueToothMainWindow::InitAbnormalErrorWidget()
{
    KyDebug();
    _MAbnormalErrorWidget = new QWidget(_MCentralWidget);
    QVBoxLayout *errorWidgetLayout = new QVBoxLayout(_MAbnormalErrorWidget);
    QLabel      *errorWidgetIcon   = new QLabel(_MAbnormalErrorWidget);
    QLabel      *errorWidgetTip    = new QLabel(_MAbnormalErrorWidget);

    _MAbnormalErrorWidget->setObjectName("abnormalErrorWidget");

    errorWidgetLayout->setSpacing(10);
    errorWidgetLayout->setMargin(0);
    errorWidgetLayout->setContentsMargins(0,0,0,0);

    errorWidgetIcon->setFixedSize(56,56);
    errorWidgetTip->resize(200,30);
    errorWidgetTip->setFont(QFont("Noto Sans CJK SC",18,QFont::Bold));

    errorWidgetLayout->addStretch(10);

    if (QIcon::hasThemeIcon("dialog-warning")) {
        errorWidgetIcon->setPixmap(QIcon::fromTheme("dialog-warning").pixmap(56,56));
        errorWidgetLayout->addWidget(errorWidgetIcon,1,Qt::AlignCenter);
    }

    errorWidgetTip->setText(tr("Bluetooth adapter is abnormal !"));
    errorWidgetLayout->addWidget(errorWidgetTip,1,Qt::AlignCenter);
    errorWidgetLayout->addStretch(10);

//    _MCentralWidget->addWidget(_MAbnormalErrorWidget);
}

void BlueToothMainWindow::InitNoAdapterErrorWidget()
{
    KyDebug();
    _MNoAdapterErrorWidget = new QWidget(_MCentralWidget);
    QVBoxLayout *errorWidgetLayout = new QVBoxLayout(_MNoAdapterErrorWidget);
    QLabel      *errorWidgetIcon   = new QLabel(_MNoAdapterErrorWidget);
    QLabel      *errorWidgetTip    = new QLabel(_MNoAdapterErrorWidget);

    _MNoAdapterErrorWidget->setObjectName("noAdapterErrorWidget");

    errorWidgetLayout->setSpacing(10);
    errorWidgetLayout->setMargin(0);
    errorWidgetLayout->setContentsMargins(0,0,0,0);

    errorWidgetIcon->setFixedSize(56,56);
    errorWidgetTip->resize(200,30);
    errorWidgetTip->setFont(QFont("Noto Sans CJK SC",18,QFont::Bold));

    errorWidgetLayout->addStretch(10);

    if (QIcon::hasThemeIcon("dialog-warning")) {
        errorWidgetIcon->setPixmap(QIcon::fromTheme("dialog-warning").pixmap(56,56));
        errorWidgetLayout->addWidget(errorWidgetIcon,1,Qt::AlignCenter);
    }

    errorWidgetTip->setText(tr("Bluetooth adapter not detected !"));
    errorWidgetLayout->addWidget(errorWidgetTip,1,Qt::AlignCenter);
    errorWidgetLayout->addStretch(10);

}

void BlueToothMainWindow::InitAdapterLoadingWidget()
{
//    KyDebug();

    _MAdapterLoadingWidget = new QWidget(_MCentralWidget);
    QVBoxLayout *loadingWidgetLayout = new QVBoxLayout(_MAdapterLoadingWidget);
    //QLabel      *loadingWidgetIcon   = new QLabel(_MAdapterLoadingWidget);
    LoadingLabel      *loadingWidgetIcon   = new LoadingLabel(_MAdapterLoadingWidget);

    _MAdapterLoadingWidget->setObjectName("adapterLoadingWidget");
    loadingWidgetLayout->setSpacing(10);
    loadingWidgetLayout->setMargin(0);
    loadingWidgetLayout->setContentsMargins(0,0,0,0);

    loadingWidgetIcon->setFixedSize(16,16);
    loadingWidgetIcon->setTimerStart();
    loadingWidgetLayout->addStretch(10);

//    m_loadingWindx = 0;
//    m_loadingWIcontimer = new QTimer(this);
//    m_loadingWIcontimer->setInterval(100);
//    connect(m_loadingWIcontimer,&QTimer::timeout,this,[=]{
//        m_loadingWindx++ ;
//        if(m_loadingWindx > 7 || m_loadingWindx < 0)
//            m_loadingWindx = 0;
//        loadingWidgetIcon->setPixmap(QIcon::fromTheme("ukui-loading-"+QString("%1").arg(m_loadingWindx)+"-symbolic").pixmap(16,16));

//    });
//    m_loadingWIcontimer->start();

//    loadingWidgetIcon->setPixmap(QIcon::fromTheme("ukui-loading-"+QString("%1").arg(m_loadingWindx)+"-symbolic").pixmap(16,16));
    loadingWidgetLayout->addWidget(loadingWidgetIcon,1,Qt::AlignCenter);
    loadingWidgetLayout->addStretch(10);

//    _MCentralWidget->addWidget(_MAdapterLoadingWidget);

    //加载蓝牙适配器
    m_loadingWBTAdapterTimer = new QTimer(this);
    m_loadingWBTAdapterTimer->setInterval(6000);
    connect(m_loadingWBTAdapterTimer,&QTimer::timeout,this,[=]{
        KyWarning()<<"m_loadingWBTAdapterTimer timeout";
        m_loadingWBTAdapterTimer->stop();
        if (_MCentralWidget->currentIndex() == MAINWINDOW_LOADING_INTERFACE)
            _MCentralWidget->setCurrentIndex(MAINWINDOW_ERROR_ADAPTER_NOT_DETECTED);
    });

    //加载蓝牙服务
    m_loadingWBTServiceTimer = new QTimer(this);
    m_loadingWBTServiceTimer->setInterval(6000);
    connect(m_loadingWBTServiceTimer,&QTimer::timeout,this,[=]{
        KyWarning()<<"m_loadingWBTAdapterTimer timeout";
        m_loadingWBTServiceTimer->stop();
        if (_MCentralWidget->currentIndex() == MAINWINDOW_LOADING_INTERFACE)
            _MCentralWidget->setCurrentIndex(MAINWINDOW_ERROR_ABNORMAL_DRIVE);
    });

}

void BlueToothMainWindow::setAdapterLoadingWidget(int m_mode)
{
    KyDebug() << m_mode ;
    _MCentralWidget->setCurrentIndex(MAINWINDOW_LOADING_INTERFACE);

//    m_loadingWindx = 0;
//    if (!m_loadingWIcontimer->isActive())
//        m_loadingWIcontimer->start();

    if (m_mode == MAINWINDOW_ERROR_ABNORMAL_DRIVE)
    {
        m_loadingWBTServiceTimer->stop();
        m_loadingWBTServiceTimer->start();
    }
    else if(m_mode == MAINWINDOW_ERROR_ADAPTER_NOT_DETECTED)
    {
        m_loadingWBTAdapterTimer->stop();
        m_loadingWBTAdapterTimer->start();
    }
}

void BlueToothMainWindow::InitNormalWidget()
{
//    KyDebug();
    _MNormalWidget = new QWidget(_MCentralWidget);
    _MNormalWidget->setObjectName("normalWidget");

    _NormalWidgetMainLayout = new QVBoxLayout(_MNormalWidget);
    _NormalWidgetMainLayout->setSpacing(40);
    _NormalWidgetMainLayout->setContentsMargins(0,0,0,10);

    _MNormalWidgetTop = new QWidget(_MNormalWidget);
    _MNormalWidgetTop->setObjectName("NormalWidgetTop");

    _MNormalWidgetMiddle = new QWidget(_MNormalWidget);
    _MNormalWidgetMiddle->setObjectName("NormalWidgetMiddle");
    //初始化隐藏
    _MNormalWidgetMiddle->hide();

    _MNormalWidgetBottom = new QWidget(_MNormalWidget);
    _MNormalWidgetBottom->setObjectName("NormalWidgetBottom");

    InitNormalWidgetTop();
    InitNormalWidgetMiddle();
    InitNormalWidgetBottom();

    _NormalWidgetMainLayout->addWidget(_MNormalWidgetTop,1,Qt::AlignTop);
    _NormalWidgetMainLayout->addWidget(_MNormalWidgetMiddle,1,Qt::AlignTop);
    _NormalWidgetMainLayout->addWidget(_MNormalWidgetBottom,1,Qt::AlignTop);
    _NormalWidgetMainLayout->addStretch(10);

//    _MCentralWidget->addWidget(_MNormalWidget);
}

void BlueToothMainWindow::InitNormalWidgetTop()
{
//    KyDebug();
    QVBoxLayout *NormalWidgetTopLayout = new QVBoxLayout(_MNormalWidgetTop);
    NormalWidgetTopLayout->setSpacing(8);
    NormalWidgetTopLayout->setContentsMargins(0,0,0,0);

    //~ contents_path /Bluetooth/Bluetooth
    QLabel *textBluetoothLabel = new QLabel(_MNormalWidgetTop);
    textBluetoothLabel->setText(tr("Bluetooth"));
    textBluetoothLabel->resize(100,25);
    textBluetoothLabel->setContentsMargins(16,0,0,0);
    NormalWidgetTopLayout->addWidget(textBluetoothLabel,1,Qt::AlignTop);

    _MNormalFrameTop = new QFrame(_MNormalWidgetTop);
    _MNormalFrameTop->setMinimumWidth(582);
    _MNormalFrameTop->setFrameShape(QFrame::Shape::Box);
    NormalWidgetTopLayout->addWidget(_MNormalFrameTop);

    QVBoxLayout *NormalFrameLayout = new QVBoxLayout(_MNormalWidgetTop);
    NormalFrameLayout->setSpacing(0);
    NormalFrameLayout->setContentsMargins(0,0,0,0);
    _MNormalFrameTop->setLayout(NormalFrameLayout);

    //================================ init BtSwitchFrame =======================================
    QFrame *BtSwitchFrame = new QFrame(_MNormalFrameTop);
    BtSwitchFrame->setMinimumWidth(582);
    BtSwitchFrame->setFrameShape(QFrame::Shape::Box);
    BtSwitchFrame->setFixedHeight(58);
//    BtSwitchFrame->setAutoFillBackground(true);
    NormalFrameLayout->addWidget(BtSwitchFrame,1,Qt::AlignTop);

    QHBoxLayout *BtSwitchFrameLayout = new QHBoxLayout(BtSwitchFrame);
    BtSwitchFrameLayout->setSpacing(0);
    BtSwitchFrameLayout->setContentsMargins(16,0,16,0);

    //~ contents_path /Bluetooth/Turn on :
    QLabel *BtSwitchLabel = new QLabel(tr("Turn on :"),BtSwitchFrame);
    BtSwitchFrameLayout->addWidget(BtSwitchLabel,1,Qt::AlignLeft);

    _BtNameLabel = new BluetoothNameLabel(BtSwitchFrame,300,38);
    BtSwitchFrameLayout->addWidget(_BtNameLabel,1,Qt::AlignLeft);

    _BtSwitchBtn = new KSwitchButton(BtSwitchFrame);
//    _BtSwitchBtn->setChecked(true);
    BtSwitchFrameLayout->addStretch(25);
    BtSwitchFrameLayout->addWidget(_BtSwitchBtn);

    //添加分割线
    BtSwitchLineFrame = new QFrame(_MNormalFrameTop);
    BtSwitchLineFrame->setFixedHeight(1);
    BtSwitchLineFrame->setMinimumWidth(582);
    BtSwitchLineFrame->setFrameStyle(QFrame::HLine);
    NormalFrameLayout->addWidget(BtSwitchLineFrame);
    //================================ end init BtSwitchFrame =======================================

    //================================ init BtAdapterListFrame ===========================================
    BtAdapterListFrame = new QFrame(_MNormalFrameTop);
    BtAdapterListFrame->setMinimumWidth(582);
    BtAdapterListFrame->setFrameShape(QFrame::Shape::Box);
    BtAdapterListFrame->setFixedHeight(58);
//    BtAdapterListFrame->setAutoFillBackground(true);
    NormalFrameLayout->addWidget(BtAdapterListFrame,1,Qt::AlignTop);

    QHBoxLayout *BtAdapterListFrameLayout = new QHBoxLayout(BtAdapterListFrame);
    BtAdapterListFrameLayout->setSpacing(0);
    BtAdapterListFrameLayout->setContentsMargins(16,0,16,0);

    //~ contents_path /Bluetooth/Adapter List
    QLabel *textAdapterListLabel = new QLabel(tr("Adapter List"),BtAdapterListFrame);
    BtAdapterListFrameLayout->addWidget(textAdapterListLabel);
    BtAdapterListFrameLayout->addStretch(10);

    _AdapterListSelectComboBox = new QComboBox(BtAdapterListFrame);
    _AdapterListSelectComboBox->clear();
    _AdapterListSelectComboBox->setMinimumWidth(300);
    BtAdapterListFrameLayout->addWidget(_AdapterListSelectComboBox);

    //添加分割线
    BtAdapterListLineFrame = new QFrame(_MNormalFrameTop);
    BtAdapterListLineFrame->setFixedHeight(1);
    BtAdapterListLineFrame->setMinimumWidth(582);
    BtAdapterListLineFrame->setFrameStyle(QFrame::HLine);
    NormalFrameLayout->addWidget(BtAdapterListLineFrame);
    //================================ end init BtAdapterListFrame =======================================

    //================================ init BtTrayIconShowFrame ===========================================
    BtTrayIconShowFrame = new QFrame(_MNormalFrameTop);
    BtTrayIconShowFrame->setMinimumWidth(582);
    BtTrayIconShowFrame->setFrameShape(QFrame::Shape::Box);
    BtTrayIconShowFrame->setFixedHeight(58);
//    BtTrayIconShowFrame->setAutoFillBackground(true);
    NormalFrameLayout->addWidget(BtTrayIconShowFrame,1,Qt::AlignTop);

    QHBoxLayout *BtTrayIconShowFrameLayout = new QHBoxLayout(BtTrayIconShowFrame);
    BtTrayIconShowFrameLayout->setSpacing(0);
    BtTrayIconShowFrameLayout->setContentsMargins(16,0,16,0);

    //~ contents_path /Bluetooth/Show icon on taskbar
    QLabel *BtTrayIconShowLabel = new QLabel(tr("Show icon on taskbar"),BtTrayIconShowFrame);
    BtTrayIconShowFrameLayout->addWidget(BtTrayIconShowLabel);

    _BtTrayIconShow = new KSwitchButton(BtTrayIconShowFrame);
    BtTrayIconShowFrameLayout->addStretch(10);
    BtTrayIconShowFrameLayout->addWidget(_BtTrayIconShow);

    BtTrayIconShowLineFrame = new QFrame(_MNormalFrameTop);
    BtTrayIconShowLineFrame->setFixedHeight(1);
    BtTrayIconShowLineFrame->setMinimumWidth(582);
    BtTrayIconShowLineFrame->setFrameStyle(QFrame::HLine);
    NormalFrameLayout->addWidget(BtTrayIconShowLineFrame);
    //================================ end init BtTrayIconShowFrame =======================================


    //================================ init BtDiscoverableFrame ===========================================
    BtDiscoverableFrame = new QFrame(_MNormalFrameTop);
    BtDiscoverableFrame->setMinimumWidth(582);
    BtDiscoverableFrame->setFrameShape(QFrame::Shape::Box);
    BtDiscoverableFrame->setFixedHeight(58);
//    BtDiscoverableFrame->setAutoFillBackground(true);
    NormalFrameLayout->addWidget(BtDiscoverableFrame,1,Qt::AlignTop);

    QHBoxLayout *BtDiscoverableFrameLayout = new QHBoxLayout(BtDiscoverableFrame);
    BtDiscoverableFrameLayout->setSpacing(0);
    BtDiscoverableFrameLayout->setContentsMargins(16,0,16,0);

    //~ contents_path /Bluetooth/Discoverable by nearby Bluetooth devices
    QLabel *BtDiscoverableLabel = new QLabel(tr("Discoverable by nearby Bluetooth devices"),BtDiscoverableFrame);
    BtDiscoverableFrameLayout->addWidget(BtDiscoverableLabel);

    _BtDiscoverable = new KSwitchButton(BtDiscoverableFrame);
    BtDiscoverableFrameLayout->addStretch(10);
    BtDiscoverableFrameLayout->addWidget(_BtDiscoverable);

    //添加分割线
    BtDiscoverableLineFrame = new QFrame(_MNormalFrameTop);
    BtDiscoverableLineFrame->setFixedHeight(1);
    BtDiscoverableLineFrame->setMinimumWidth(582);
    BtDiscoverableLineFrame->setFrameStyle(QFrame::HLine);
    NormalFrameLayout->addWidget(BtDiscoverableLineFrame);
    //================================ end init BtDiscoverableFrame =======================================

    //================================ init BtAutomaticAudioConnectionFrame ===========================================
    BtAutomaticAudioConnectionFrame = new QFrame(_MNormalFrameTop);
    BtAutomaticAudioConnectionFrame->setMinimumWidth(582);
    BtAutomaticAudioConnectionFrame->setFrameShape(QFrame::Shape::Box);
    BtAutomaticAudioConnectionFrame->setFixedHeight(58);
//    BtAutomaticAudioConnectionFrame->setAutoFillBackground(true);
    NormalFrameLayout->addWidget(BtAutomaticAudioConnectionFrame,1,Qt::AlignTop);

    QHBoxLayout *BtAutomaticAudioConnectionFrameLayout = new QHBoxLayout(BtAutomaticAudioConnectionFrame);
    BtAutomaticAudioConnectionFrameLayout->setSpacing(0);
    BtAutomaticAudioConnectionFrameLayout->setContentsMargins(16,0,16,0);

    //~ contents_path /Bluetooth/Auto discover Bluetooth audio devices
    QLabel *BtAutomaticAudioConnectionLabel = new QLabel(tr("Auto discover Bluetooth audio devices"),BtAutomaticAudioConnectionFrame);
    BtAutomaticAudioConnectionFrameLayout->addWidget(BtAutomaticAudioConnectionLabel);

    _BtAutoAudioConnBtn = new KSwitchButton(BtDiscoverableFrame);
    BtAutomaticAudioConnectionFrameLayout->addStretch(10);
    BtAutomaticAudioConnectionFrameLayout->addWidget(_BtAutoAudioConnBtn);
    //================================ end init BtAutomaticAudioConnectionFrame =======================================

    NormalWidgetTopLayout->addStretch(2);


}

void BlueToothMainWindow::InitNormalWidgetMiddle()
{
//    KyDebug();
    QVBoxLayout *NormalWidgetMiddleLayout = new QVBoxLayout(_MNormalWidgetMiddle);
    NormalWidgetMiddleLayout->setSpacing(8);
    NormalWidgetMiddleLayout->setContentsMargins(0,0,0,0);

    //~ contents_path /Bluetooth/My Devices
    QLabel *MyDevicesLabel = new QLabel(_MNormalWidgetMiddle);
    MyDevicesLabel->setText(tr("My Devices"));
    MyDevicesLabel->resize(72,25);
    MyDevicesLabel->setContentsMargins(16,0,0,0);
    NormalWidgetMiddleLayout->addWidget(MyDevicesLabel,Qt::AlignTop);

    _MNormalFrameMiddle = new QFrame(_MNormalWidgetMiddle);
    _MNormalFrameMiddle->setMinimumWidth(582);
    _MNormalFrameMiddle->setFrameShape(QFrame::Shape::Box);
    _MNormalFrameMiddle->setContentsMargins(0,0,0,0);
    NormalWidgetMiddleLayout->addWidget(_MNormalFrameMiddle,1,Qt::AlignTop);

    _NormalWidgetPairedDevLayout = new QVBoxLayout(_MNormalFrameMiddle);
    _NormalWidgetPairedDevLayout->setSpacing(0);
    _NormalWidgetPairedDevLayout->setContentsMargins(0,0,0,0);
    _MNormalFrameMiddle->setLayout(_NormalWidgetPairedDevLayout);

}

void BlueToothMainWindow::InitNormalWidgetBottom()
{
    KyDebug();
    QVBoxLayout *_MNormalWidgetBottomLayout = new QVBoxLayout(_MNormalWidgetBottom);
    _MNormalWidgetBottomLayout->setSpacing(8);
    _MNormalWidgetBottomLayout->setContentsMargins(0,0,0,0);

    QHBoxLayout *titleLayout = new QHBoxLayout(_MNormalWidgetBottom);
    titleLayout->setSpacing(0);
    titleLayout->setContentsMargins(0,0,0,0);

    //~ contents_path /Bluetooth/Bluetooth Devices
    QLabel *OtherDevicesLabel = new QLabel(_MNormalWidgetBottom);
    OtherDevicesLabel->setText(tr("Bluetooth Devices"));
    OtherDevicesLabel->resize(72,25);
    OtherDevicesLabel->setContentsMargins(16,0,10,0);

    titleLayout->addWidget(OtherDevicesLabel, 1, Qt::AlignLeft);

    _LoadIcon = new LoadingLabel(_MNormalWidgetBottom);
    _LoadIcon->setFixedSize(16,16);
    _LoadIcon->setTimerStart();
    titleLayout->addWidget(_LoadIcon, 1, Qt::AlignLeft);

    _DevTypeSelectComboBox = new QComboBox(_MNormalWidgetBottom);
    _DevTypeSelectComboBox->clear();
    _DevTypeSelectComboBox->addItems(devTypeSelectStrList);
    currentShowTypeFlag = _DEV_TYPE(_DevTypeSelectComboBox->currentIndex());

    titleLayout->addStretch(25);
    titleLayout->addWidget(_DevTypeSelectComboBox, 1, Qt::AlignRight);
    _MNormalWidgetBottomLayout->addLayout(titleLayout);

    _MNormalFrameBottom = new QFrame(_MNormalWidgetBottom);
    _MNormalFrameBottom->setMinimumWidth(582);
    _MNormalFrameBottom->setFrameShape(QFrame::Shape::Box);
    _MNormalFrameBottom->setContentsMargins(0,0,0,0);
    _MNormalWidgetBottomLayout->addWidget(_MNormalFrameBottom,1,Qt::AlignTop);

    _NormalWidgetCacheDevLayout  = new QVBoxLayout(_MNormalFrameBottom);
    _NormalWidgetCacheDevLayout->setSpacing(0);
    _NormalWidgetCacheDevLayout->setContentsMargins(0,0,0,0);
    _NormalWidgetCacheDevLayout->setAlignment(Qt::AlignTop);
    _MNormalFrameBottom->setLayout(_NormalWidgetCacheDevLayout);

}

void BlueToothMainWindow::InitInterfaceUIStatus()
{
    KyDebug();
    if (nullptr == BlueToothDBusService::m_default_bluetooth_adapter)
    {
        KyWarning()<< " BlueToothDBusService::m_default_bluetooth_adapter is nullptr!";
        //异常处理
        _MCentralWidget->setCurrentIndex(MAINWINDOW_ERROR_ADAPTER_NOT_DETECTED);
        return ;
    }

    //top===========

    //bluetooth
    _BtNameLabel->set_dev_name(BlueToothDBusService::m_default_bluetooth_adapter->getDevName());
    KyWarning()<< "power status:" << BlueToothDBusService::m_default_bluetooth_adapter->getAdapterPower();
    _BtSwitchBtn->setChecked(BlueToothDBusService::m_default_bluetooth_adapter->getAdapterPower());

    //开关界面显示加载
    BtSwitchLineFrame->setVisible(_BtSwitchBtn->isChecked());
    if (BlueToothDBusService::m_bluetooth_adapter_name_list.size() > 1)
    {
        BtAdapterListFrame->setVisible(_BtSwitchBtn->isChecked());
        BtAdapterListLineFrame->setVisible(_BtSwitchBtn->isChecked());
    }

    BtTrayIconShowFrame->setVisible(_BtSwitchBtn->isChecked());
    BtTrayIconShowLineFrame->setVisible(_BtSwitchBtn->isChecked());

    BtDiscoverableFrame->setVisible(_BtSwitchBtn->isChecked());
    BtDiscoverableLineFrame->setVisible(_BtSwitchBtn->isChecked());

    BtAutomaticAudioConnectionFrame->setVisible(_BtSwitchBtn->isChecked());

    //bluetooth adapter list
    KyWarning() << "m_bluetooth_adapter_name_list::" << BlueToothDBusService::m_bluetooth_adapter_name_list;
    if (BlueToothDBusService::m_bluetooth_adapter_name_list.size() <= 1)
    {
        _AdapterListSelectComboBox->clear();
        _AdapterListSelectComboBox->addItems(BlueToothDBusService::m_bluetooth_adapter_name_list);
        BtAdapterListFrame->hide();
        BtAdapterListLineFrame->hide();
    }
    else
    {
        _AdapterListSelectComboBox->clear();
        _AdapterListSelectComboBox->addItems(BlueToothDBusService::m_bluetooth_adapter_name_list);
        _AdapterListSelectComboBox->setCurrentText(BlueToothDBusService::m_default_bluetooth_adapter->getDevName());

        BtAdapterListFrame->setVisible(_BtSwitchBtn->isChecked());
        BtAdapterListLineFrame->setVisible(_BtSwitchBtn->isChecked());
    }

    //show taskbar
    _BtTrayIconShow->setChecked(BlueToothDBusService::m_default_bluetooth_adapter->getAdapterTrayShow());

    //discoverable
    KyWarning()<< "_BtDiscoverable::" << _BtDiscoverable->isChecked() << BlueToothDBusService::m_default_bluetooth_adapter->getAdapterDiscoverable();
    _BtDiscoverable->setChecked(BlueToothDBusService::m_default_bluetooth_adapter->getAdapterDiscoverable());

    //auto audio conncet
    _BtAutoAudioConnBtn->setChecked(BlueToothDBusService::m_default_bluetooth_adapter->getAdapterAutoConn());

    //Middle===========
    clearMyDevicesUI();
    QList<QString> pairedDevKeyList = BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list.keys(); // 存放的就是QMap的key值
    KyDebug() << pairedDevKeyList;
    for(QString dev_addr:pairedDevKeyList)
    {
        if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_addr]->isPaired())
            addMyDeviceItemUI(dev_addr);
    }
    _MNormalWidgetMiddle->setVisible(_BtSwitchBtn->isChecked() && _MyDevicesInterfaceShowFlags);

    //Bottom===========
    clearOtherDevicesUI();
    QList<QString> devKeyList = BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list.keys(); // 存放的就是QMap的key值
    KyDebug() << devKeyList;
    for(QString dev_addr:devKeyList)
    {
        if(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list.contains(dev_addr) && !BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_addr]->isPaired())
            addOneBluetoothDeviceItemUi(dev_addr);
    }

    _MNormalWidgetBottom->setVisible(_BtSwitchBtn->isChecked());
    _LoadIcon->setVisible(_BtSwitchBtn->isChecked());

    if (_BtSwitchBtn->isChecked())
        _LoadIcon->setTimerStart();
    else
        _LoadIcon->setTimerStop();

}

void BlueToothMainWindow::InitInterfaceUISignalBinding()
{
    KyDebug();

    //name label
    connect(_BtNameLabel,&BluetoothNameLabel::sendAdapterName,this,&BlueToothMainWindow::setDefaultAdapterNameSlot);
    //connect(this,&BlueToothMain::defaultAdapterNameChanged,bluetooth_name,&BluetoothNameLabel::setLabelText);

    //btn
    connect(_BtSwitchBtn,SIGNAL(stateChanged(bool)),this,SLOT(_BtSwitchBtnSlot(bool)));
    connect(_BtTrayIconShow,SIGNAL(stateChanged(bool)),this,SLOT(_BtTrayIconShowSlot(bool)));
    connect(_BtDiscoverable,SIGNAL(stateChanged(bool)),this,SLOT(_BtDiscoverableSlot(bool)));
    connect(_BtAutoAudioConnBtn,SIGNAL(stateChanged(bool)),this,SLOT(_BtAutoAudioConnBtnSlot(bool)));

    //ComboBox
    connect(_AdapterListSelectComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(_AdapterListSelectComboBoxSlot(int)));
    connect(_DevTypeSelectComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(_DevTypeSelectComboBoxSlot(int)));

}

void BlueToothMainWindow::InitBluetoothServiceSignalBinding()
{
    KyDebug();

    if (nullptr != btServer)
    {
        connect(btServer,SIGNAL(adapterAddSignal(QString)),this,SLOT(adapterAddSlot(QString)));
        connect(btServer,SIGNAL(adapterRemoveSignal(int)),this,SLOT(adapterRemoveSlot(int)));
        connect(btServer,SIGNAL(defaultAdapterChangedSignal(int)),this,SLOT(defaultAdapterChangedSlot(int)));
        //adapter status change
        connect(btServer,SIGNAL(adapterNameChanged(QString)),this,SLOT(adapterNameChangedSlot(QString)));
        connect(btServer,SIGNAL(adapterPoweredChanged(bool)),this,SLOT(adapterPowerStatusChangedSlot(bool)));
        connect(btServer,SIGNAL(adapterTrayIconChanged(bool)),this,SLOT(adapterTrayIconSlot(bool)));
        connect(btServer,SIGNAL(adapterDiscoverableChanged(bool)),this,SLOT(adapterDiscoverableSlot(bool)));
        connect(btServer,SIGNAL(adapterActiveConnectionChanged(bool)),this,SLOT(adapterActiveConnectionSlot(bool)));
        connect(btServer,SIGNAL(adapterDiscoveringChanged(bool)),this,SLOT(adapterDiscoveringSlot(bool)));

        connect(btServer,SIGNAL(deviceAddSignal(QString)),this,SLOT(deviceAddSlot(QString)));
        connect(btServer,SIGNAL(deviceRemoveSignal(QString)),this,SLOT(deviceRemoveSlot(QString)));
        connect(btServer,SIGNAL(devicePairedSuccess(QString)),this,SLOT(devicePairedSuccessSlot(QString)));

        //bt service update
        connect(btServer,SIGNAL(btServiceRestart()),this,SLOT(btServiceRestartSlot()));
        connect(btServer,SIGNAL(btServiceRestartComplete(bool)),this,SLOT(btServiceRestartCompleteSlot(bool)));

    }
}

void BlueToothMainWindow::adapterAddSlot(QString adapter_name)
{
    KyDebug() << adapter_name << BlueToothDBusService::m_bluetooth_adapter_address_list.size();
    KyWarning() << "adapter_name:" << adapter_name
                << "BlueToothDBusService::m_bluetooth_adapter_address_list:" << BlueToothDBusService::m_bluetooth_adapter_address_list
                << "size :" << BlueToothDBusService::m_bluetooth_adapter_address_list.size() ;

    if(BlueToothDBusService::m_bluetooth_adapter_address_list.size())
    {
        _AdapterListSelectComboBox->addItem(adapter_name);
        if(BlueToothDBusService::m_bluetooth_adapter_address_list.size() >1)
        {
            if (BtAdapterListFrame->isHidden())
                BtAdapterListFrame->setVisible(_BtSwitchBtn->isChecked());
            if (BtAdapterListLineFrame->isHidden())
                BtAdapterListLineFrame->setVisible(_BtSwitchBtn->isChecked());
        }
    }

    if (MAINWINDOW_NORMAL_INTERFACE != _MCentralWidget->currentIndex())
    {
        _MCentralWidget->setCurrentIndex(MAINWINDOW_LOADING_INTERFACE);
        int indx = 0;
        foreach (auto bt_val,BlueToothDBusService::m_bluetooth_adapter_address_list)
        {
            if (bt_val == BlueToothDBusService::m_default_bluetooth_adapter->getDevAddress())
                break;
            indx++;
        }
        KyWarning() << "adapter indx:"<< indx << "_MCentralWidget name:" << _MCentralWidget->currentIndex() ;

        adapterChangedRefreshInterface(indx);
        _MCentralWidget->setCurrentIndex(MAINWINDOW_NORMAL_INTERFACE);
    }
}

void BlueToothMainWindow::adapterRemoveSlot(int indx)
{
    KyDebug() << indx <<
                   BlueToothDBusService::m_bluetooth_adapter_name_list.size() <<
                   BlueToothDBusService::m_bluetooth_adapter_name_list;
    KyWarning() << indx <<
                   BlueToothDBusService::m_bluetooth_adapter_name_list.size() <<
                   BlueToothDBusService::m_bluetooth_adapter_name_list;

    if(0 >= BlueToothDBusService::m_bluetooth_adapter_name_list.size())
    {
        if (_BtSwitchBtn->isChecked())
        {
            _BTServiceReportPowerSwitchFlag = true;
            Q_EMIT _BtSwitchBtn->stateChanged(false);
        }

        _MCentralWidget->setCurrentIndex(MAINWINDOW_LOADING_INTERFACE);
        m_loadingWBTAdapterTimer->start();
    }
    else if (1 == BlueToothDBusService::m_bluetooth_adapter_name_list.size())
    {
        BtAdapterListFrame->hide();
        BtAdapterListLineFrame->hide();

        bool flag = false ;
        if (indx == _AdapterListSelectComboBox->currentIndex())
        {
            flag = true;
            _AdapterListSelectComboBox->disconnect();
        }

        _AdapterListSelectComboBox->removeItem(indx);

        if(flag)
            connect(_AdapterListSelectComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(_AdapterListSelectComboBoxSlot(int)));

    }
    else
    {
        BtAdapterListFrame->show();
        BtAdapterListLineFrame->show();
        bool flag = false ;
        if (indx == _AdapterListSelectComboBox->currentIndex())
        {
            flag = true;
            _AdapterListSelectComboBox->disconnect();
        }

        _AdapterListSelectComboBox->removeItem(indx);

        if (flag)
            connect(_AdapterListSelectComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(_AdapterListSelectComboBoxSlot(int)));

    }

}

void BlueToothMainWindow::adapterChangedRefreshInterface(int indx)
{
    KyDebug() << indx;
    if (!BlueToothDBusService::m_default_bluetooth_adapter)
        KyWarning() << "m_default_bluetooth_adapter is nullptr!";

    if(BlueToothDBusService::m_default_bluetooth_adapter->getAdapterPower() != _BtSwitchBtn->isChecked())
        _BTServiceReportPowerSwitchFlag = true;

    if(BlueToothDBusService::m_default_bluetooth_adapter->getAdapterTrayShow() != _BtTrayIconShow->isChecked())
        _BTServiceReportTrayIconSwitchFlag = true;

    if(BlueToothDBusService::m_default_bluetooth_adapter->getAdapterDiscoverable() != _BtDiscoverable->isChecked())
        _BTServiceReportDiscoverableSwtichFlag = true;

    if(BlueToothDBusService::m_default_bluetooth_adapter->getAdapterAutoConn() != _BtAutoAudioConnBtn->isChecked())
        _BTServiceReportAutoAudioConnSwtichFlag = true;

    _AdapterListSelectComboBox->disconnect();
    InitInterfaceUIStatus();
    _AdapterListSelectComboBox->setCurrentIndex(indx);
    connect(_AdapterListSelectComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(_AdapterListSelectComboBoxSlot(int)));

}

void BlueToothMainWindow::defaultAdapterChangedSlot(int indx)
{
    KyDebug() << indx;
    //清除我的设备和其他设备界面
//    clearMyDevicesUI();
//    clearOtherDevicesUI();

    adapterChangedRefreshInterface(indx);
}

void BlueToothMainWindow::deviceAddSlot(QString dev_address)
{
    KyDebug();

    if (MAINWINDOW_NORMAL_INTERFACE != _MCentralWidget->currentIndex())
    {
        KyWarning() << _MCentralWidget->currentIndex() <<__LINE__;
        return;
    }

    if (BlueToothDBusService::m_default_bluetooth_adapter && BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list.contains(dev_address))
    {
        if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_address]->isPaired())
        {
            KyDebug() << dev_address << ":dev is pair!" ;
            addMyDeviceItemUI(dev_address);
        }
        else
        {
            if (_LoadIcon->isHidden())
            {
                _LoadIcon->show();
                _LoadIcon->setTimerStart();
            }

            KyDebug() << dev_address << ":dev is not pair!" ;
            addOneBluetoothDeviceItemUi(dev_address);
        }
    }
}


void BlueToothMainWindow::removeMDevFrameLineFrame(QString str)
{
    KyDebug();

    if ("paired" == str)
    {
        if ((_MNormalFrameMiddle->findChildren<QFrame *>().size() - _MNormalFrameMiddle->findChildren<bluetoothdeviceitem *>().size() - 3) ==
                _MNormalFrameMiddle->findChildren<bluetoothdeviceitem *>().size())
        {
            QLayoutItem *child;
            if ((child = _NormalWidgetPairedDevLayout->takeAt(0)) != 0)
            {
                if (child->widget()->objectName().startsWith("line-"))
                {
                    delete child->widget();
                    delete child;
                }
            }
        }
    }
    else if ("other" == str)
    {

    }
    else
    {
        return;
    }
}

void BlueToothMainWindow::removeBluetoothDeviceItemUi(QString address)
{
    KyDebug() << address ;

    //移除蓝牙设备列表的设备
    bluetoothdeviceitem *item = _MNormalFrameBottom->findChild<bluetoothdeviceitem *>(address);
    if(item)
    {
        KyDebug() << item->objectName();
        _NormalWidgetCacheDevLayout->removeWidget(item);
        item->disconnect();
        //item->setParent(NULL);
        item->deleteLater();
    }
    else
    {
        KyDebug() << "bluetooth device list NULL!!";
    }

    QFrame *line_item = _MNormalFrameBottom->findChild<QFrame *>("line-"+address);
    if(line_item) {
        KyDebug() << line_item->objectName();
        _NormalWidgetCacheDevLayout->removeWidget(line_item);
        //line_item->setParent(NULL);
        line_item->deleteLater();
    }

    //移除已配对设备列表的设备
    item = _MNormalFrameMiddle->findChild<bluetoothdeviceitem *>(address);
    line_item = _MNormalFrameMiddle->findChild<QFrame *>("line-"+address);
    if(item)
    {
        _NormalWidgetPairedDevLayout->removeWidget(item);
        item->disconnect();
        //item->setParent(NULL);
        item->deleteLater();

        if (line_item)
        {
            _NormalWidgetPairedDevLayout->removeWidget(line_item);
            //line_item->setParent(NULL);
            line_item->deleteLater();
        }
        else
            removeMDevFrameLineFrame("paired");

        KyDebug() << "paired_dev_layout->count():" << _NormalWidgetPairedDevLayout->count() ;
        if(!_NormalWidgetPairedDevLayout->count()){
            _MyDevicesInterfaceShowFlags = false;
            _MNormalWidgetMiddle->hide();
        }
        else
        {
            _MyDevicesInterfaceShowFlags = true;
            if(_BtSwitchBtn->isChecked())
                _MNormalWidgetMiddle->show();
            else
                _MNormalWidgetMiddle->hide();

        }
    }
    else
    {
        KyDebug() << "pair list is NULL";
        return;
    }

    for(auto it = devShowOrderListVec.begin(); it != devShowOrderListVec.end() ;++it)
    {
        if (it->first == address)
        {
            KyDebug() << devShowOrderListVec;
            devShowOrderListVec.removeAll(fruit(it->first,it->second));
            KyDebug()  << devShowOrderListVec;
            break;
        }
    }
    KyDebug() << "remove Item UI end" ;

}

void BlueToothMainWindow::deviceRemoveSlot(QString dev_address)
{
    KyDebug() << dev_address;
    removeBluetoothDeviceItemUi(dev_address);
}

void BlueToothMainWindow::devicePairedSuccessSlot(QString dev_address)
{
    KyDebug() << dev_address ;

    //判断我的设备中是否存在该设备界面
    bluetoothdeviceitem *my_item = _MNormalFrameMiddle->findChild<bluetoothdeviceitem *>(dev_address);
    if (my_item)
    {
        KyDebug() << dev_address << "：my item exist!";
        return;
    }

    //判断其他设备中是否存在该设备界面
    bluetoothdeviceitem *other_item = _MNormalFrameBottom->findChild<bluetoothdeviceitem *>(dev_address);
    if (other_item)
    {
        KyDebug() << dev_address << "：other item exist!";
        return;
    }
    else
    {
        KyDebug() << dev_address << ": item not exist!";
        addMyDeviceItemUI(dev_address);
    }
}

void BlueToothMainWindow::setDefaultAdapterNameSlot(QString name)
{
    KyDebug();
    BlueToothDBusService::setDefaultAdapterName(name);
}

void BlueToothMainWindow::_BtSwitchBtnSlot(bool status)
{
    KyDebug();


    BtSwitchLineFrame->setVisible(status);
    if (BlueToothDBusService::m_bluetooth_adapter_name_list.size() > 1)
    {
        BtAdapterListFrame->setVisible(status);
        BtAdapterListLineFrame->setVisible(status);
    }

    BtTrayIconShowFrame->setVisible(status);
    BtTrayIconShowLineFrame->setVisible(status);

    BtDiscoverableFrame->setVisible(status);
    BtDiscoverableLineFrame->setVisible(status);

    BtAutomaticAudioConnectionFrame->setVisible(status);

    if (!_MyDevicesInterfaceShowFlags)
        _MNormalWidgetMiddle->hide();
    else
        _MNormalWidgetMiddle->setVisible(status);
    _MNormalWidgetBottom->setVisible(status);

    KyInfo() << "_BTServiceReportPowerSwitchFlag:" << _BTServiceReportPowerSwitchFlag ;
    if(!_BTServiceReportPowerSwitchFlag)//服务上报的状态不再次下发
    {
        ukccbluetoothconfig::ukccBtBuriedSettings(QString("Bluetooth"),QString("BtSwitchBtn"),QString("clicked"),status?QString("true"):QString("false"));
        BlueToothDBusService::setDefaultAdapterSwitchStatus(status);
    }
    else
        _BTServiceReportPowerSwitchFlag = false;

}

void BlueToothMainWindow::adapterPowerStatusChangedSlot(bool status)
{
    KyDebug() << status ;
    if(MAINWINDOW_NORMAL_INTERFACE == _MCentralWidget->currentIndex())
    {
        KyWarning() << "_BTServiceReportPowerSwitchFlag:"<<  _BTServiceReportPowerSwitchFlag ;
        _BTServiceReportPowerSwitchFlag = true;
        KyWarning() << "_BtSwitchBtn->isChecked:"<<  _BtSwitchBtn->isChecked() ;
//        _BtSwitchBtnSlot(status);
        //Q_EMIT _BtSwitchBtn->stateChanged(status);
        if(status != _BtSwitchBtn->isChecked())
            _BtSwitchBtn->setChecked(status);
        else
            Q_EMIT _BtSwitchBtn->stateChanged(status);
    }

}

void BlueToothMainWindow::adapterNameChangedSlot(QString name)
{
    KyDebug() << name ;
    _BtNameLabel->set_dev_name(name);
}

void BlueToothMainWindow::_BtTrayIconShowSlot(bool status)
{
    KyDebug();

    if(!_BTServiceReportTrayIconSwitchFlag)//服务上报的状态不再次下发
    {
        ukccbluetoothconfig::ukccBtBuriedSettings(QString("Bluetooth"),QString("BtTrayIconShow"),QString("clicked"),status?QString("true"):QString("false"));
        BlueToothDBusService::setTrayIconShowStatus(status);
    }
    else
        _BTServiceReportTrayIconSwitchFlag = false;

}

void BlueToothMainWindow::adapterTrayIconSlot(bool status)
{
    KyDebug();
    if(MAINWINDOW_NORMAL_INTERFACE == _MCentralWidget->currentIndex())
    {
        _BTServiceReportTrayIconSwitchFlag = true;
        if(status != _BtTrayIconShow->isChecked())
            _BtTrayIconShow->setChecked(status);
        else
            Q_EMIT _BtTrayIconShow->stateChanged(status);
            //_BtTrayIconShowSlot(status);
    }

}

void BlueToothMainWindow::_BtDiscoverableSlot(bool status)
{
    KyDebug();
    if(!_BTServiceReportDiscoverableSwtichFlag)
    {
        ukccbluetoothconfig::ukccBtBuriedSettings(QString("Bluetooth"),QString("BtDiscoverable"),QString("clicked"),status?QString("true"):QString("false"));
        BlueToothDBusService::setDefaultAdapterDiscoverableStatus(status);
    }
    else
        _BTServiceReportDiscoverableSwtichFlag = false;

}

void BlueToothMainWindow::adapterDiscoverableSlot(bool status)
{
    KyDebug();
    if(MAINWINDOW_NORMAL_INTERFACE == _MCentralWidget->currentIndex())
    {
        _BTServiceReportDiscoverableSwtichFlag = true;
//        _BtDiscoverable->setChecked(status);
//        Q_EMIT _BtDiscoverable->stateChanged(status);
        if(status != _BtDiscoverable->isChecked())
            _BtDiscoverable->setChecked(status);
        else
            Q_EMIT _BtDiscoverable->stateChanged(status);

    }
}

void BlueToothMainWindow::_BtAutoAudioConnBtnSlot(bool status)
{
    KyDebug();


    if(!_BTServiceReportAutoAudioConnSwtichFlag)
    {
        ukccbluetoothconfig::ukccBtBuriedSettings(QString("Bluetooth"),QString("BtAutoAudioConnBtn"),QString("clicked"),status?QString("true"):QString("false"));
        BlueToothDBusService::setAutoConnectAudioDevStatus(status);
    }
    else
        _BTServiceReportAutoAudioConnSwtichFlag = false;
}

void BlueToothMainWindow::adapterActiveConnectionSlot(bool status)
{
    KyDebug();
    if(MAINWINDOW_NORMAL_INTERFACE == _MCentralWidget->currentIndex())
    {
        _BTServiceReportAutoAudioConnSwtichFlag = true;

        if(status != _BtAutoAudioConnBtn->isChecked())
            _BtAutoAudioConnBtn->setChecked(status);
        else
            Q_EMIT _BtAutoAudioConnBtn->stateChanged(status);
    }
}

void BlueToothMainWindow::adapterDiscoveringSlot(bool status)
{
    KyDebug() << status;

    if(MAINWINDOW_NORMAL_INTERFACE == _MCentralWidget->currentIndex())
    {
        _LoadIcon->setVisible(status);
        if (status)
            _LoadIcon->setTimerStart();
        else
            _LoadIcon->setTimerStop();
    }

}

void BlueToothMainWindow::_AdapterListSelectComboBoxSlot(int indx)
{
    KyDebug() << indx << BlueToothDBusService::m_bluetooth_adapter_address_list.size()  << BlueToothDBusService::m_bluetooth_adapter_address_list;
    //KyWarning() << indx << BlueToothDBusService::m_bluetooth_adapter_address_list.size() << BlueToothDBusService::m_bluetooth_adapter_address_list;
    ukccbluetoothconfig::ukccBtBuriedSettings(QString("Bluetooth"),QString("AdapterListSelectComboBox"),QString("settings"),QString::number(indx));

    if (BlueToothDBusService::m_bluetooth_adapter_address_list.size() > indx)
    {
        KyInfo() << BlueToothDBusService::m_bluetooth_adapter_address_list.at(indx);
        BlueToothDBusService::setDefaultAdapter(BlueToothDBusService::m_bluetooth_adapter_address_list.at(indx));
    }

}

void BlueToothMainWindow::clearMyDevicesUI()
{
    KyDebug();
    //清空列表数据
    QLayoutItem *child;

    while(_NormalWidgetPairedDevLayout->count()!=0)
    {
        child = _NormalWidgetPairedDevLayout->takeAt(0);
        if(child->widget() != 0)
        {
            delete child->widget();
        }
        delete child;
    }

    _MyDevicesInterfaceShowFlags = false;
    _MNormalWidgetMiddle->setVisible(_BtSwitchBtn->isChecked() && _MyDevicesInterfaceShowFlags);


}


void BlueToothMainWindow::clearOtherDevicesUI()
{
    KyDebug();
    //清空列表数据
    QLayoutItem *child;
    while(_NormalWidgetCacheDevLayout->count()!=0)
    {
        child = _NormalWidgetCacheDevLayout->takeAt(0);
        if(child->widget() != 0)
        {
            delete child->widget();
        }
        delete child;
    }
    devShowOrderListVec.clear();


}

void BlueToothMainWindow::_DevTypeSelectComboBoxSlot(int indx)
{
    KyDebug() << indx;

    ukccbluetoothconfig::ukccBtBuriedSettings(QString("Bluetooth"),QString("DevTypeSelectComboBox"),QString("settings"),QString::number(indx));

    currentShowTypeFlag = _DEV_TYPE(indx);
    //清空列表数据
    QLayoutItem *child;

    while(_NormalWidgetCacheDevLayout->count()!=0)
    {
        child = _NormalWidgetCacheDevLayout->takeAt(0);
        if(child->widget() != 0)
        {
            delete child->widget();
        }
        delete child;
    }

    devShowOrderListVec.clear();

    reloadDeviceListItem(currentShowTypeFlag);


}

void BlueToothMainWindow::btServiceRestartSlot()
{
    KyDebug();
    _MCentralWidget->setCurrentIndex(MAINWINDOW_LOADING_INTERFACE);
//    if (m_loadingWIcontimer->isActive())
//    {
//        m_loadingWindx = 0;
//        m_loadingWIcontimer->stop();
//        m_loadingWIcontimer->start();
//    }
//    else
//    {
//        m_loadingWindx = 0;
//        m_loadingWIcontimer->start();
//    }

    if (m_loadingWBTServiceTimer->isActive())
    {
        m_loadingWBTServiceTimer->stop();
        m_loadingWBTServiceTimer->start();
    }
    else
        m_loadingWBTServiceTimer->start();

}

void BlueToothMainWindow::btServiceRestartCompleteSlot(bool status)
{
    KyDebug() << status;

    if (m_loadingWBTServiceTimer->isActive())
        m_loadingWBTServiceTimer->stop();

    if (status)
    {
        int indx = 0 ;
        foreach (auto var, BlueToothDBusService::m_bluetooth_adapter_address_list) {
            if (var == BlueToothDBusService::m_default_bluetooth_adapter->getDevAddress())
                break;
            indx++;
        }
        KyDebug() << indx;

        adapterChangedRefreshInterface(indx);
        if(MAINWINDOW_LOADING_INTERFACE == _MCentralWidget->currentIndex())
            _MCentralWidget->setCurrentIndex(MAINWINDOW_NORMAL_INTERFACE);

    }
    else
    {
        if(MAINWINDOW_LOADING_INTERFACE == _MCentralWidget->currentIndex())
            _MCentralWidget->setCurrentIndex(MAINWINDOW_ERROR_ABNORMAL_DRIVE);
    }
}

bool BlueToothMainWindow::isEffectiveDevice(QString devName , bluetoothdevice::DEVICE_TYPE devType)
{
    KyDebug() << devName << devType ;
    if ((devName.split(":").length() == 6 || devName.split("-").length() == 6) && bluetoothdevice::DEVICE_TYPE::uncategorized == devType)
    {
        return false;
    }
    else
    {
        return true;
    }
}

bool BlueToothMainWindow::whetherToDisplayInTheCurrentInterface(bluetoothdevice::DEVICE_TYPE devType)
{
    KyDebug() << devType << _DEV_TYPE(_DevTypeSelectComboBox->currentIndex()) ;
    if (nullptr != _DevTypeSelectComboBox)
        currentShowTypeFlag = _DEV_TYPE(_DevTypeSelectComboBox->currentIndex());
    if(_DEV_TYPE::BT_All == currentShowTypeFlag)//显示为全部设备时，直接返回true
    {
        KyDebug() << "currentShowTypeFlag:" << currentShowTypeFlag ;
        return true;
    }

    _DEV_TYPE temp_dev_type ;

    if (devType == bluetoothdevice::DEVICE_TYPE::headset ||
        devType == bluetoothdevice::DEVICE_TYPE::headphones ||
        devType == bluetoothdevice::DEVICE_TYPE::audiovideo) {
        temp_dev_type = BT_Audio;
    }
    else if (devType == bluetoothdevice::DEVICE_TYPE::mouse ||
             devType == bluetoothdevice::DEVICE_TYPE::keyboard) {
        temp_dev_type = BT_Peripherals;

    }
    else if (devType == bluetoothdevice::DEVICE_TYPE::computer) {
        temp_dev_type = BT_Computer;
    }
    else if (devType == bluetoothdevice::DEVICE_TYPE::phone) {
        temp_dev_type = BT_Phone;
    }
    else
    {
        temp_dev_type = BT_Other;
    }

    KyInfo() << "currentShowTypeFlag:" << currentShowTypeFlag <<  "temp_dev_type:" << temp_dev_type ;

    if (currentShowTypeFlag == temp_dev_type)
    {
        KyInfo() << Q_FUNC_INFO << "true" ;
        return true;
    }
    else
    {
        KyInfo() << Q_FUNC_INFO << "false" ;
        return false;
    }
}

void BlueToothMainWindow::reloadDeviceListItem(BlueToothMainWindow::_DEV_TYPE flag)
{
    KyDebug() << flag;
    if (!BlueToothDBusService::m_default_bluetooth_adapter)
    {
        KyWarning() << "m_default_bluetooth_adapter is NULL!" ;
        return ;
    }
    KyInfo() << BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list;

    QList<QString> devKeyList = BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list.keys(); // 存放的就是QMap的key值
    for (QString dev_addr : devKeyList)
    {
        if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_addr]->isPaired())
            continue;
        switch (flag) {
        case _DEV_TYPE::BT_All:
            addOneBluetoothDeviceItemUi(dev_addr);
            break;
        case _DEV_TYPE::BT_Audio:
            if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_addr]->getDevType() == bluetoothdevice::DEVICE_TYPE::headset ||
                BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_addr]->getDevType() == bluetoothdevice::DEVICE_TYPE::headphones ||
                BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_addr]->getDevType() == bluetoothdevice::DEVICE_TYPE::audiovideo) {
                addOneBluetoothDeviceItemUi(dev_addr);
            }
            break;
        case _DEV_TYPE::BT_Peripherals:
            if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_addr]->getDevType() == bluetoothdevice::DEVICE_TYPE::mouse ||
                BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_addr]->getDevType() == bluetoothdevice::DEVICE_TYPE::keyboard) {
                addOneBluetoothDeviceItemUi(dev_addr);
            }
            break;
        case _DEV_TYPE::BT_Computer:
            if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_addr]->getDevType() == bluetoothdevice::DEVICE_TYPE::computer) {
                addOneBluetoothDeviceItemUi(dev_addr);
            }
            break;
        case _DEV_TYPE::BT_Phone:
            if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_addr]->getDevType() == bluetoothdevice::DEVICE_TYPE::phone) {
                addOneBluetoothDeviceItemUi(dev_addr);
            }
            break;
        case _DEV_TYPE::BT_Other:
            if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_addr]->getDevType() == bluetoothdevice::DEVICE_TYPE::headset ||
                BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_addr]->getDevType() == bluetoothdevice::DEVICE_TYPE::headphones ||
                BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_addr]->getDevType() == bluetoothdevice::DEVICE_TYPE::audiovideo ||
                BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_addr]->getDevType() == bluetoothdevice::DEVICE_TYPE::phone ||
                BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_addr]->getDevType() == bluetoothdevice::DEVICE_TYPE::mouse ||
                BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_addr]->getDevType() == bluetoothdevice::DEVICE_TYPE::keyboard ||
                BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_addr]->getDevType() == bluetoothdevice::DEVICE_TYPE::computer)
                break;
            else
                addOneBluetoothDeviceItemUi(dev_addr);
            break;
        default:
            addOneBluetoothDeviceItemUi(dev_addr);
            break;
        }
    }
}

void BlueToothMainWindow::frameAddLineFrame(int indx,QString str,QString addr)
{
    KyDebug() << "#########################" << indx << str << addr;
    if ("paired_list" == str)
    {
        if (!_MNormalFrameMiddle->findChildren<bluetoothdeviceitem *>().size())
        {
            return;
        }

        QFrame *line_frame = new QFrame(_MNormalFrameMiddle);
        line_frame->setObjectName("line-"+addr);
        line_frame->setFixedHeight(1);
        line_frame->setMinimumWidth(582);
        line_frame->setFrameStyle(QFrame::HLine);
        _NormalWidgetPairedDevLayout->addWidget(line_frame,1,Qt::AlignTop);

    }
    else if ("device_list" == str)
    {
        if (!_MNormalFrameBottom->findChildren<bluetoothdeviceitem *>().size())
        {
            return;
        }
        QFrame *line_frame = new QFrame(_MNormalFrameBottom);
        line_frame->setObjectName("line-"+addr);
        line_frame->setFixedHeight(1);
        line_frame->setMinimumWidth(582);
        line_frame->setFrameStyle(QFrame::HLine);

        if (!_MNormalFrameBottom->isVisible())
            _MNormalFrameBottom->setVisible(true);

        _NormalWidgetCacheDevLayout->insertWidget(indx,line_frame,1,Qt::AlignTop);

    }
    else
    {
        return;
    }
}

void BlueToothMainWindow::addMyDeviceItemUI(QString device_address)
{
    KyDebug() << device_address;

    if (nullptr == BlueToothDBusService::m_default_bluetooth_adapter ||
        !BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list.contains(device_address) ||
        !BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[device_address]->isPaired())
    {
        KyWarning() << "device is not Paired!";
        return;
    }

    _MyDevicesInterfaceShowFlags = true;
    if(_MyDevicesInterfaceShowFlags)
    {
        if(_MNormalWidgetMiddle->isVisible() != _BtSwitchBtn->isChecked())
            _MNormalWidgetMiddle->setVisible(_BtSwitchBtn->isChecked());
    }

    bluetoothdeviceitem *item  = _MNormalWidgetMiddle->findChild<bluetoothdeviceitem *>(device_address);
    if (item)
    {
        KyInfo() << "device is exist" ;
        return;
    }

    frameAddLineFrame(0,"paired_list",device_address);
    item = new bluetoothdeviceitem(_MNormalWidgetMiddle,device_address);
    connect(item,&bluetoothdeviceitem::bluetoothDeviceItemRemove,this,[=](QString address)
    {
        KyDebug() <<  item->objectName() << address ;
        deviceRemoveSlot(address);
    });

    _NormalWidgetPairedDevLayout->addWidget(item,Qt::AlignTop);
}

void BlueToothMainWindow::adjustDeviceDisplayPosition(QString address,quint16 rssiValue)
{
    KyDebug()<< address << rssiValue ;
    //判断界面是否需要调整位置
    int old_devIndx = 0;
    for(auto it = devShowOrderListVec.begin() ; it != devShowOrderListVec.end() ; ++it)
    {
        if(it->first == address)
            break;
        old_devIndx++;
    }

    int new_devIndx = getDevRssiItemInsertIndex(rssiValue);
    //和原有位置做对比
    if (new_devIndx == old_devIndx ||  new_devIndx-1 == old_devIndx)
    {
        KyDebug() << "No change in position" ;
        return ;
    }

    bluetoothdeviceitem *new_item = _MNormalFrameBottom->findChild<bluetoothdeviceitem *>(address);
    QFrame *line_item = _MNormalFrameBottom->findChild<QFrame *>("line-"+address);
    if(new_item)
    {
        _NormalWidgetCacheDevLayout->removeWidget(new_item);
        if(line_item) {
            _NormalWidgetCacheDevLayout->removeWidget(line_item);
            line_item->setParent(NULL);
            line_item->deleteLater();
        }
    }

    int countIndx = 0;
    for(auto it = devShowOrderListVec.begin() ; it != devShowOrderListVec.end() ; ++it)
    {
        if(it->first == address)
        {
            devShowOrderListVec.removeAt(countIndx);
            break;
        }
        countIndx++;
    }

    int insert_index = getDevRssiItemInsertIndex(rssiValue);
    //KyInfo()  << "insert_index:"<< insert_index ;

    if (insert_index == -1)
    {
        devShowOrderListVec.append(fruit(address,rssiValue));
        insert_index = _NormalWidgetCacheDevLayout->count();
    }
    else
    {
        devShowOrderListVec.insert(insert_index,fruit(address,rssiValue));
        insert_index = insert_index*2;
        if (insert_index > _NormalWidgetCacheDevLayout->count())
            insert_index = _NormalWidgetCacheDevLayout->count();
    }

    frameAddLineFrame(insert_index,"device_list",address);
    _NormalWidgetCacheDevLayout->insertWidget(insert_index,new_item,1,Qt::AlignTop);

}

void BlueToothMainWindow::addOneBluetoothDeviceItemUi(QString dev_address)
{
    KyDebug();
    //设备不存在
    if(!BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list.contains(dev_address))
    {
        KyDebug() << "device is NULL!";
        return ;
    }
    //非法设备/和当前显示界面类型选择不一致
    if (/*!isEffectiveDevice(device->getDevName(),device->getDevType()) ||*/
            !whetherToDisplayInTheCurrentInterface(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_address]->getDevType()))
    {
        KyDebug() << "Inconsistent with the display type!" ;
        return ;
    }

    //设备界面已存在
    bluetoothdeviceitem * item  = _MNormalFrameBottom->findChild<bluetoothdeviceitem *>(dev_address);
    if (item)
    {
        KyDebug() << "device is exist" ;
        return;
    }

    item = new bluetoothdeviceitem(_MNormalFrameBottom,dev_address);
    connect(item,&bluetoothdeviceitem::devPairedSuccess,this,[=](QString address)
    {
        KyDebug() <<  item->objectName() << address ;
        changeDeviceParentWindow(address);
    });

    connect(item,&bluetoothdeviceitem::devRssiChanged,this,[=](qint64 value)
    {
        KyDebug() << item->objectName() << value ;
        //显示位置调整
        adjustDeviceDisplayPosition(item->objectName(),value);
    });
    connect(item,&bluetoothdeviceitem::bluetoothDeviceItemRemove,this,[=](QString address)
    {
        KyDebug() <<  item->objectName() << address ;
        deviceRemoveSlot(address);
    });

    if (!_MNormalFrameBottom->isVisible())
        _MNormalFrameBottom->setVisible(true);

    int insert_index = getDevRssiItemInsertIndex(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_address]->getDevRssi());
    KyDebug() << "insert_index:"<< insert_index ;
    KyDebug() << devShowOrderListVec;

    if (insert_index == -1)
    {
        devShowOrderListVec.append(fruit(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_address]->getDevAddress(),BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_address]->getDevRssi()));
        insert_index = _NormalWidgetCacheDevLayout->count();
    }
    else
    {
        devShowOrderListVec.insert(insert_index,fruit(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_address]->getDevAddress(),BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[dev_address]->getDevRssi()));
        insert_index = insert_index*2;
        if (insert_index > _NormalWidgetCacheDevLayout->count())
            insert_index = _NormalWidgetCacheDevLayout->count();
    }

    frameAddLineFrame(insert_index,"device_list",dev_address);
    _NormalWidgetCacheDevLayout->insertWidget(insert_index,item,1,Qt::AlignTop);
}

void BlueToothMainWindow::changeDeviceParentWindow(const QString &address)
{
    KyDebug() << address ;
    if(!_MNormalWidgetMiddle->isVisible()){
        _MNormalWidgetMiddle->setVisible(_BtSwitchBtn->isChecked() && true);
        _MyDevicesInterfaceShowFlags = true;
    }

    bluetoothdeviceitem *item = _MNormalFrameBottom->findChild<bluetoothdeviceitem *>(address);
    QFrame *line_item = _MNormalFrameBottom->findChild<QFrame *>("line-"+address);
    if(item)
    {
        frameAddLineFrame(0,"paired_list",address);
        _NormalWidgetCacheDevLayout->removeWidget(item);
        item->setParent(_MNormalFrameMiddle);

        if(line_item) {
            _NormalWidgetCacheDevLayout->removeWidget(line_item);
            //line_item->setParent(NULL);
            line_item->deleteLater();
        }
        _NormalWidgetPairedDevLayout->addWidget(item);
    }
    else
    {
        return;
    }
}

int BlueToothMainWindow::getDevRssiItemInsertIndex(qint16 currDevRssi)
{
    KyDebug() << "currDevRssi："<< currDevRssi ;
    //KyDebug () << "devShowOrderListVec:"<< devShowOrderListVec ;

    for(auto it = devShowOrderListVec.begin() ; it != devShowOrderListVec.end() ; ++it)
    {
        //KyDebug()  << "it->first(address):"<< it->first << "it->second(rssi):"<< it->second ;
        if (it->second <= currDevRssi)
        {
            //KyDebug() << "========index:"<< devShowOrderListVec.indexOf(fruit(it->first,it->second)) ;
            return (devShowOrderListVec.indexOf(fruit(it->first,it->second)));
        }
    }
    return -1;
}

